package hash_map_set;

/**
 * Created with IntelliJ IDEA.
 * Description: 实现 hashCode方法
 * User: 86187
 * Date: 2022-08-22
 * Time: 18:07
 */

public class HashCode<K,V> {
    static class Node<K, V> {
        public K key;
        public V val;
        public Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K, V>[] elem = (Node<K, V>[]) new Node[2];
    public int usedSize;

    public static final float DEFAULT_LOAD_FACTOR = 0.75F; //hash 负载因子

    /**
     * 存储 key 和 val
     */
    public void put(K key, V val) {
        Node<K, V> node = new Node<>(key, val);

        int hash = key.hashCode();
        int index = hash % elem.length;

        Node<K, V> cur = elem[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.val = val;
            }
            cur = cur.next;
        }
        node.next = elem[index];
        elem[index] = node;

        this.usedSize++;
    }

    private float loadFactor() {
        return 1.0F * this.usedSize / elem.length;
    }
    private void growSize() {
        Node<K,V>[] newElem = (Node<K,V>[]) new Node[elem.length*2];
        /**
         *  1.遍历数组的每个元素的链表
         *  2.每遍历一个节点 就重新哈希 key.hashCode() % newElem.length
         *  3.进行头插法
         */
        for (int i = 0; i < elem.length; i++) {
            Node<K,V> cur = elem[i];
            while(cur != null) {
                //找到新的位置
                int index = cur.key.hashCode() % newElem.length;
                Node<K,V> nextNode = cur.next;

                //头插
                cur.next = newElem[index];
                newElem[index] = cur;

                cur = nextNode;
            }
        }
        this.elem = newElem;
    }



    /**
     * 通过 key 获取 val的值
     */
    public V get(K key) {
        int index = key.hashCode() % elem.length;

        Node<K, V> cur = elem[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
